// edit.js
Page({
  data: {
    docId: null,
    docTitle: '',
    docContent: '',
    historyVersions: [], // Array of historical versions
    selectedVersion: null, // Currently previewed version
    showHistory: false, // Toggle for timeline visibility
    versionCounter: 1 // Counter for sequential version numbering
  },

  onLoad: function (options) {
    const { id } = options;
    this.setData({ docId: id });
    this.loadDocument(id);
    this.loadHistoryVersions(id);
  },

  // Load the current document
  loadDocument: function (id) {
    const doc = wx.getStorageSync(`document_${id}`);
    if (doc) {
      this.setData({
        docTitle: doc.title,
        docContent: doc.content
      });
    }
  },

  // Format timestamp to readable date-time
  formatTimestamp: function (timestamp) {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
  },

  // Load historical versions, filtering to past 30 days
  loadHistoryVersions: function (id) {
    const historyKey = `document_${id}_history`;
    const historyVersions = wx.getStorageSync(historyKey) || [];
    const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
    const recentVersions = historyVersions.filter(v => v.timestamp >= thirtyDaysAgo);
    
    // Sort versions by timestamp and reassign versionId sequentially
    recentVersions.sort((a, b) => a.timestamp - b.timestamp);
    recentVersions.forEach((v, index) => {
      v.versionId = index + 1; // Reassign versionId as 1, 2, 3...
      v.formattedTime = this.formatTimestamp(v.timestamp); // Add formatted time
    });
    
    this.setData({ historyVersions: recentVersions });
  },

  // Handle title input
  onTitleInput: function (e) {
    this.setData({ docTitle: e.detail.value });
  },

  // Handle content input
  onContentInput: function (e) {
    this.setData({ docContent: e.detail.value });
  },

  // Save document and update version history
  saveDocument: function () {
    const { docId, docTitle, docContent } = this.data;
    if (!docTitle) {
      wx.showToast({ title: '请输入文档标题', icon: 'none' });
      return;
    }
    const doc = { title: docTitle, content: docContent };
    wx.setStorageSync(`document_${docId}`, doc);
    this.addHistoryVersion(docId, doc);
    wx.showToast({ title: '保存成功', icon: 'success' });
  },

  // Add a new version to history
  addHistoryVersion: function (docId, doc) {
    const historyKey = `document_${docId}_history`;
    let historyVersions = wx.getStorageSync(historyKey) || [];
    let { versionCounter } = this.data;

    const newVersion = {
      versionId: versionCounter, // Use sequential number
      timestamp: Date.now(),
      title: doc.title,
      content: doc.content,
      summary: 'Edited document', // Could be enhanced with diff logic
      formattedTime: this.formatTimestamp(Date.now()) // Add formatted time
    };
    historyVersions.push(newVersion);

    // Filter out versions older than 30 days
    const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
    historyVersions = historyVersions.filter(v => v.timestamp >= thirtyDaysAgo);
    
    // Reassign versionId sequentially after filtering
    historyVersions.sort((a, b) => a.timestamp - b.timestamp);
    historyVersions.forEach((v, index) => {
      v.versionId = index + 1; // Reassign versionId as 1, 2, 3...
      v.formattedTime = this.formatTimestamp(v.timestamp); // Add formatted time
    });

    wx.setStorageSync(historyKey, historyVersions);
    this.setData({
      historyVersions: historyVersions,
      versionCounter: versionCounter + 1 // Increment counter for next version
    });
  },

  // Toggle history timeline visibility
  showHistory: function () {
    this.setData({ showHistory: true });
  },

  // Select a version for preview
  selectVersion: function (e) {
    const versionId = Number(e.currentTarget.dataset.versionId); // Ensure numeric comparison
    const selectedVersion = this.data.historyVersions.find(v => v.versionId === versionId);
    this.setData({ selectedVersion });
  },

  // Restore to selected version
  restoreVersion: function () {
    const { selectedVersion, docId } = this.data;
    if (!selectedVersion) return;

    wx.showModal({
      title: '确认恢复',
      content: '确定恢复到此版本吗？',
      success: (res) => {
        if (res.confirm) {
          const doc = { title: selectedVersion.title, content: selectedVersion.content };
          wx.setStorageSync(`document_${docId}`, doc);
          this.addHistoryVersion(docId, doc); // Record restoration as new version
          this.setData({
            docTitle: doc.title,
            docContent: doc.content,
            selectedVersion: null,
            showHistory: false
          });
          wx.showToast({ title: '恢复成功', icon: 'success' });
        }
      }
    });
  },

  // Close history view
  closeHistory: function () {
    this.setData({ showHistory: false, selectedVersion: null });
  },

  // Close preview view, keep history timeline
  closePreview: function () {
    this.setData({ selectedVersion: null });
  },

  // Prevent event propagation
  stopPropagation: function () {
    // This function is used to prevent event bubbling
  }
});